import React, { PureComponent, Fragment } from 'react';
import {
  Drawer,
  Col,
  Row,
  Tabs, Button, Icon,
} from 'antd';
import { connect } from 'dva';
import groupBy from 'lodash/groupBy';
import forEach from 'lodash/forEach';
import ReactDataGrid from 'react-data-grid';
import find from 'lodash/find';
import styles from './../ValveFlowMeterSite/index.less'
import gold_groud from './../../images/valve_small.png'
import gold_groud2 from './../../images/valve2_small.jpg'
import unknow from './../../images/unknow.png'

const { TabPane } = Tabs;

@connect(({ devices, loading }) => ({
  devices,
}))
class BasicList extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      group: {},
      groupNameMap: {
        'press_sensor': '压力传感器',
        'pipe': '现状管道',
        'water': '水厂监控设备',
        'workstations1': '双阀减压阀井',
        'appendage': '附属物',
        'characteristic': '特征',
      },
    };
  }


  componentDidMount() {
    const group = groupBy(this.props.selectFeature, 'ground_set');
    console.log('group', group);
    this.setState({
      group,
    });

  }

  componentWillUnmount() {
  }

  renderStatus = (val) => {
    let type = '';
    let color = '';
    let text = '';
    switch (val) {
      case 1:
        type = 'check-circle', color = '#004cff', text = '在线';
        break;
      case -1:
        type = 'close-circle', color = '#fe1b2e', text = '离线';
        break;
      default:
        type = 'close-circle', color = '#eb2f96', text = '异常';
        break;
    }
    return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
  };
  renderTabPane = (group) => {
    const that = this;
    const defaultColumnProperties = {
      resizable: true,
    };
    const defaultColumnProperties2 = {
      resizable: true,
      sortable: true,
    };
    const columns = [
      {
        name: '压力传感器名称',
        width: 190,
        key: 'name',

      },
      {
        name: 'IMEI',
        key: 'imei',
        width: 130,
      },
      {
        name: '安装地址',
        width: 150,
        key: 'address',
      },
      {
        name: '在线状态',
        key: 'online_status',
        width: 80,
        formatter: (event) => {
          return this.renderStatus(event.value);
        },
      },
      {
        name: '创建时间',
        width: 150,
        key: 'created_at',
      },
      {
        name: '操作',
        width: 100,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            className={'btn-cyan'}
            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              e.stopPropagation();
              this.props.showDetail(event.row);
            }
            }
          >详情
          </Button>
        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties, ...c }));

    const pipeColumns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          return <p className={'index'}>{(event.value + 1)}</p>;
        },
      },
      {
        name: 'ID',
        width: 80,
        key: 'id',
        sortDescendingFirst: true,

      },
      {
        name: '起点埋深(m)',
        key: '起点埋深',
        width: 100,
      },
      {
        name: '终点埋深(m)',
        key: '终点埋深',
        width: 100,
      },
      {
        name: '材质',
        key: '材质',
        width: 90,
        sortDescendingFirst: true,
      },
      {
        name: '埋设方式',
        key: '埋设方式',
        width: 95,
      },
      {
        name: '线型',
        key: '线型',
        width: 100,
      },
      {
        name: '管径',
        key: '管径',
        width: 85,
        sortDescendingFirst: true,
      },
      {
        name: '长度(m)',
        key: '长度',
        width: 100,
        formatter: (event) => <Fragment>
          {event.value.toFixed(2)}
        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties2, ...c }));
    const appendageCharcColumns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          return <p className={'index'}>{(event.value + 1)}</p>;
        },
      },
      {
        name: '管点编号',
        width: 80,
        key: '管点编号',
        sortDescendingFirst: true,
      },
      {
        name: '附属物',
        key: '附属物',
        width: 100,
      },
      {
        name: '特征',
        key: '特征',
        width: 100,
      },

      {
        name: '地面高程',
        key: '地面高程',
        width: 90,
      },
      {
        name: '井底埋深',
        key: '井底埋深',
        width: 95,
      },
      {
        name: '井盖类型',
        key: '井盖类型',
        width: 100,
      },
      {
        name: '井盖材质',
        key: '井盖材质',
        width: 85,
      },
      {
        name: '精度级别',
        key: '精度级别',
        width: 85,
      },
      {
        name: '备注',
        key: '备注',
        width: 85,
      },
    ].map(c => ({ ...defaultColumnProperties2, ...c }));

    let result = [];
    for (let key  in group) {
      if (key === 'press_sensor') {
        result.push(
          <TabPane tab={<span>{this.state.groupNameMap[key]}({group[key].length})</span>} key={key}>
            <ReactDataGrid
              columns={columns}
              rowGetter={i => group[key][i]}
              rowsCount={group[key].length}
              minHeight={400}

            />
          </TabPane>,
        );
      } else if (key === 'pipe') {
        let totalLength = 0;
        for (let i = 0; i < group[key].length; i++) {
          totalLength += Number(group[key][i]['长度']);
        }
        result.push(
          <TabPane tab={<span>{this.state.groupNameMap[key]}({group[key].length})</span>} key={key}>
            <ReactDataGrid
              columns={pipeColumns}
              rowGetter={i => {
                return { ...group[key][i], _index: i };
              }}
              rowsCount={group[key].length}
              minHeight={400}
              onGridSort={(sortColumn, sortDirection) => {
                const comparer = (a, b) => {
                  if (sortDirection === 'ASC') {
                    return a[sortColumn] > b[sortColumn] ? 1 : -1;
                  } else if (sortDirection === 'DESC') {
                    return a[sortColumn] < b[sortColumn] ? 1 : -1;
                  }
                };
                const parseData = sortDirection === 'NONE' ? group[key] : [...group[key]].sort(comparer);
                that.setState({
                  group: {
                    ...that.state.group,
                    pipe: parseData,
                  },
                });
              }

              }
            />
            <h2 style={{
              float: 'right',
              overflow: 'hidden',
              marginTop: '5px',
              marginBottom: '0',
              marginRight: '5px',
            }}>管道总长度: {totalLength.toFixed(2)} 米</h2>
          </TabPane>,
        );
      }  else if (key === 'appendage'||key === 'characteristic') {
        let totalLength = 0;
        for (let i = 0; i < group[key].length; i++) {
          totalLength += Number(group[key][i]['长度']);
        }
        result.push(
          <TabPane tab={<span>{this.state.groupNameMap[key]}({group[key].length})</span>} key={key}>
            <ReactDataGrid
              columns={appendageCharcColumns}
              rowGetter={i => {
                return { ...group[key][i], _index: i };
              }}
              rowsCount={group[key].length}
              minHeight={436}
              onGridSort={(sortColumn, sortDirection) => {
                const comparer = (a, b) => {
                  if (sortDirection === 'ASC') {
                    return a[sortColumn] > b[sortColumn] ? 1 : -1;
                  } else if (sortDirection === 'DESC') {
                    return a[sortColumn] < b[sortColumn] ? 1 : -1;
                  }
                };
                const parseData = sortDirection === 'NONE' ? group[key] : [...group[key]].sort(comparer);
                that.setState({
                  group: {
                    ...that.state.group,
                    appendage: parseData,
                  },
                });
              }

              }
            />
          </TabPane>,
        );
      } else if (key === 'water') {
        console.log('group[key]',group[key])
        result.push(
          <TabPane tab={<span>{this.state.groupNameMap[key]}</span>} key={key}>
            <div style={{minHeight:'400px'}}>
              <Row  gutter={16}>
                {
                  group[key].map((item,index)=>{
                    if(item.item1){
                      return    <Col span={8} key={index}>
                        <h3 style={{marginTop:'5px',fontWeight:'bold'}}>园艺场沉沙池
                          <span
                            onClick={()=>this.props.showWaterDetail('园艺场沉沙池')}
                            style={{cursor:'pointer',fontSize:'12px',float:'right',marginTop:'3px'}}>
                            查看详情
                          </span>
                        </h3>
                        <div className="pop-content pop-content2" >
                          <div className="item">
                            <li>液位(m)</li>
                            <li>浊度(NTU)</li>
                          </div>
                          <div className="item2">
                            <li>{item.item1}</li>
                            <li>{item.item2}</li>
                          </div>
                        </div>
                      </Col>
                    }else if(item.item3){
                      return    <Col span={8} key={index}>
                        <h3 style={{marginTop:'5px',fontWeight:'bold'}}>塔尔郎水厂
                          <span
                            onClick={()=>this.props.showWaterDetail('塔尔郎水厂')}
                            style={{cursor:'pointer',fontSize:'12px',float:'right',marginTop:'3px'}}>
                            查看详情
                          </span>
                        </h3>
                        <div className="pop-content pop-content2" >
                          <div className="item">
                            <li>进水流量(m³/h)</li>
                            <li>出水流量(m³/h)</li>
                            <li>取水口浊度(NTU)</li>
                          </div>
                          <div className="item2">
                            <li>{item.item3}</li>
                            <li>{item.item4}</li>
                            <li>{item.item5}</li>
                          </div>
                        </div>
                      </Col>
                    }else if(item.item6){
                      return    <Col span={8} key={index}>
                        <h3 style={{marginTop:'5px',fontWeight:'bold'}}>老城区水厂
                          <span
                            onClick={()=>this.props.showWaterDetail('老城区水厂')}
                            style={{cursor:'pointer',fontSize:'12px',float:'right',marginTop:'3px'}}>
                            查看详情
                          </span>
                        </h3>
                        <div className="pop-content pop-content2">
                          <div className="item">
                            <li>出水流量(m³/h)</li>
                            <li>1#液位(m)</li>
                            <li>2#/3#液位(m)</li>

                          </div>
                          <div className="item2">
                            <li>{item.item8}</li>
                            <li>{item.item7}</li>
                            <li>{item.item6}</li>
                          </div>
                        </div>
                      </Col>
                    }else if(item.item9){
                      return    <Col span={8} key={index}>
                        <h3 style={{marginTop:'5px',fontWeight:'bold'}}>示范区水厂
                          <span
                            onClick={()=>this.props.showWaterDetail('示范区水厂')}
                            style={{cursor:'pointer',fontSize:'12px',float:'right',marginTop:'3px'}}>
                            查看详情
                          </span>
                        </h3>
                        <div className="pop-content pop-content2" >
                          <div className="item">
                            <li>出水流量(m³/h)</li>
                            <li>液位(m)</li>
                          </div>
                          <div className="item2">
                            <li>{item.item10}</li>
                            <li>{item.item9}</li>
                          </div>
                        </div>
                      </Col>
                    }
                  })
                }
              </Row>
            </div>
          </TabPane>,
        );
      }else if (key === 'workstations1') {
        console.log('group[key]',group[key])
        result.push(
          <TabPane tab={<span>{this.state.groupNameMap[key]}</span>} key={key}>
          <Row className={'img-data-content'} gutter={[16, 16]} style={{height:'400px',maxHeight:'400px',overflow:'auto',overflowX:'hidden'}}>
            {
              group[key].map((item,index)=>{
                let borderTopColor='#5e83bf';
                switch (index%4) {
                  case 0:
                    borderTopColor='#e77338';
                    break;
                  case 1:
                    borderTopColor='#5e83bf';
                    break;
                  case 2:
                    borderTopColor='#31b77d';
                    break;
                  case 3:
                    borderTopColor='#C790E1';
                    break;

                }
                let statusText='';
                if(item.online_status===1){
                  statusText=<span style={{background:'#00b209',padding:'1px 4px',color:'#fff'}}>在线</span>
                }else if(item.online_status===-1){
                  statusText=<span style={{background:'red',padding:'1px 4px',color:'#fff'}}>离线</span>
                }
                let alarmText='';
                if(item.alarm===0){
                  alarmText=<span style={{background:'#00b209',padding:'1px 4px',color:'#fff'}}>无报警</span>
                }else if(item.online_status===1){
                  alarmText=<span style={{background:'red',padding:'1px 4px',color:'#fff'}}>报警</span>
                }
                let template='未知';
                if(item.template===1){
                  template='双阀减压阀井'
                }
                let locationImage=unknow;
                if(item.template===1){
                  locationImage=gold_groud2
                }
                return   <Col className="gutter-row" md={6} lg={6} xl={6} xxl={4} key={index}>
                 <div className={styles.img_box} style={{
                   border: '1px solid #ccc',padding:'5px',borderTopColor:borderTopColor}}>
                   <img style={{cursor:'pointer'}} onClick={()=>{
                     that.props.showWorkstationDetail(item)
                   }} src={locationImage} alt=""/>
                   <h4>站点名称 :  {item.name}</h4>
                   <h4 title={`站点IMEI :  ${item.imei}`}>站点IMEI :  {item.imei}</h4>
                   <h4>在线状态 :  {statusText}</h4>
                   <h4>是否报警 :  {alarmText}</h4>
                   <div className={styles.card_type } >
                     {template}
                   </div>
                 </div>
                </Col>
              })
            }
          </Row>

          </TabPane>,
        );
      }

    }
    return result;
  };

  render() {
    const { dispatch } = this.props;
    return <div>
      <Tabs type="card">
        {
          this.renderTabPane(this.state.group)
        }
      </Tabs>
    </div>;
  }
}

export default BasicList;
